package com.lihepeng.leecode.linkedList;

/**
 * 删除最后的一个节点，只能遍历一次
 *
 * @author lihepeng
 */
public class DeleteLastNode {
    /**
     * 定义两个节点，A节点先走，B 节点随后，等A节点到最后的时候删除B当前节点
     *
     * @param head
     * @param n
     */
    public ListNode deleteNode(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode nodeA = dummy;
        ListNode nodeB = dummy;
        int currentCount = 1;
        while (nodeA != null) {
            if (currentCount >= n) {
                nodeB = nodeB.next;
            }
            nodeA = nodeA.next;
            currentCount++;
        }
        // 删除B节点下一个数值
        nodeB.next = nodeB.next.next;
        return dummy.next;
    }
}
